﻿#pragma once
#include "MdbStructs.h"
#include "MdbIndexComp.h"
#include <set>

using std::multiset;

namespace mdb
{
	class TickTable;
	class TickIndexInstrumentID
	{
		using iterator = std::multiset<Tick*, TickLessForInstrumentIDIndex>::iterator;
		friend class TickTable;
	public:
		TickIndexInstrumentID(TickTable* table);
		iterator LowerBound(const InstrumentIDType& InstrumentID);
		iterator UpperBound(const InstrumentIDType& InstrumentID);
		std::pair<iterator, iterator> EqualRange(const InstrumentIDType& InstrumentID);
	public:
		static constexpr unsigned int IndexID = 0x0000;
	protected:
		void Insert(Tick* const record);
		void Erase(Tick* const record);
		void Update(iterator it);
		bool NeedUpdate(const Tick* const oldRecord, const Tick* const newRecord);
		iterator FindNode(Tick* const record);
		void FillCompareRecord(const InstrumentIDType& InstrumentID);

	private:
		TickTable* m_Table;
		multiset<Tick*, TickLessForInstrumentIDIndex> m_Index;
	};
	
	class BarTable;
	class BarIndexInstrumentID
	{
		using iterator = std::multiset<Bar*, BarLessForInstrumentIDIndex>::iterator;
		friend class BarTable;
	public:
		BarIndexInstrumentID(BarTable* table);
		iterator LowerBound(const Int64Type& TradingDay, const ExchangeIDType& ExchangeID, const InstrumentIDType& InstrumentID);
		iterator UpperBound(const Int64Type& TradingDay, const ExchangeIDType& ExchangeID, const InstrumentIDType& InstrumentID);
		std::pair<iterator, iterator> EqualRange(const Int64Type& TradingDay, const ExchangeIDType& ExchangeID, const InstrumentIDType& InstrumentID);
	public:
		static constexpr unsigned int IndexID = 0x0000;
	protected:
		void Insert(Bar* const record);
		void Erase(Bar* const record);
		void Update(iterator it);
		bool NeedUpdate(const Bar* const oldRecord, const Bar* const newRecord);
		iterator FindNode(Bar* const record);
		void FillCompareRecord(const Int64Type& TradingDay, const ExchangeIDType& ExchangeID, const InstrumentIDType& InstrumentID);

	private:
		BarTable* m_Table;
		multiset<Bar*, BarLessForInstrumentIDIndex> m_Index;
	};
	
	class BarIndexTradingDay
	{
		using iterator = std::multiset<Bar*, BarLessForTradingDayIndex>::iterator;
		friend class BarTable;
	public:
		BarIndexTradingDay(BarTable* table);
		iterator LowerBound(const Int64Type& TradingDay);
		iterator UpperBound(const Int64Type& TradingDay);
		std::pair<iterator, iterator> EqualRange(const Int64Type& TradingDay);
	public:
		static constexpr unsigned int IndexID = 0x0001;
	protected:
		void Insert(Bar* const record);
		void Erase(Bar* const record);
		void Update(iterator it);
		bool NeedUpdate(const Bar* const oldRecord, const Bar* const newRecord);
		iterator FindNode(Bar* const record);
		void FillCompareRecord(const Int64Type& TradingDay);

	private:
		BarTable* m_Table;
		multiset<Bar*, BarLessForTradingDayIndex> m_Index;
	};
	
}
